<?php

class ApiHelper extends Helper {

    private $_tokenfield;

    public function __construct() {
        $this->_tokenfield = array('tk_uid', 'tk_token', 'tk_expiration');
    }
    /**
     * token生成
     * @param type $uid
     */
    public function apiSave($uid){
        $model = $this->LoadModel('Public');
        $where = array('`tk_uid` = ?' => $uid);
        $api_check = $model->getOneRow('api_token', $this->_tokenfield, $where);
        $data = array(
            'tk_uid' => $uid,
            'tk_token' => strtoupper(StringCode::RandomCode(64)),
            'tk_expiration' => NOW_TIME + 86400
        );
        if(empty($api_check)){
            $model->save('api_token', $data);
        }else{
            $model->update('api_token', $data, $where);
        }
        return $data;
    }
    
    public function logSave($action, $params = array()){
        $data['l_dateline'] = NOW_TIME;
        $data['l_action'] = $action;
        $data['l_params'] = serialize($params);
        if (isset($params['uid'])){
            $data['l_uid'] = $params['uid'];
        }
        $model = $this->LoadModel('Public');
        return $model->save('api_log', $data);
    }
    
    public function tokenCheck($params){
        $model = $this->LoadModel('Public');
        $where = array('`tk_uid` = ?' => $params['uid']);
        $api_check = $model->getOneRow('api_token', $this->_tokenfield, $where);
        if(empty($api_check)){
            return array('success' => false , 'msg' => '不存在当前用户API信息', 'code' => 10010);
        }else{
            if($api_check['tk_token'] != $params['token']){
                return array('success' => false , 'msg' => 'TOKEN信息值错误[当前账号已被登陆]', 'code' => 10011);
            }
            if($api_check['tk_expiration'] < NOW_TIME){
                return array('success' => false , 'msg' => 'TOKEN已失效，请重新请求', 'code' => 10012);
            }
        }
        return array('success' => true);
    }
}